﻿using System;
using System.Linq;
using System.Text;

namespace MicroMq.Helper
{
    /// <summary>
    /// 字节读取器
    /// </summary>
    ref struct ByteReadBuffer
    {

        private Span<byte> buffer;

        private int offset;

        public ByteReadBuffer(Span<byte> buffer)
        {

            this.buffer = buffer;
            this.offset = 0;
        }

        public void Reset()
        {
            offset = 0;
        }

        public bool IsEnd => offset + 1 >= buffer.Length;


        public bool IsEmpty => buffer.Length == 0;

        /// <summary>
        /// 读取一个字节
        /// </summary>
        /// <returns></returns>
        public byte ReadByte()
        {
            return buffer[offset++];
        }

        /// <summary>
        /// 读取字节数组
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public byte[] ReadBytes(int length)
        {
            offset += length;
            return buffer.Slice(offset - length, length).ToArray();
        }

        /// <summary>
        /// 全部读取
        /// </summary>
        /// <returns></returns>
        public byte[] ReadEnd()
        {
            return ReadBytes(buffer.Length - offset);
        }

        /// <summary>
        /// 读取一段字符
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public string ReadString(int length)
        {
            return ReadString(length, Encoding.UTF8);
        }

        public string ReadUnknownString()
        {
            var length = ReadInt();
            return ReadString(length, Encoding.UTF8);
        }

        public string ReadString(int length, Encoding encoding)
        {
            return encoding.GetString(ReadBytes(length));
        }

        /// <summary>
        /// 左边开始的转Int
        /// </summary>
        /// <returns></returns>
        public int ReadInt()
        {
            return BitConverter.ToInt32(ReadBytes(4));
        }


        /// <summary>
        /// 左边开始的转Int
        /// </summary>
        /// <returns></returns>
        public long ReadLong()
        {
            return BitConverter.ToInt64(ReadBytes(8));
        }

        /// <summary>
        /// 包裹一个读取器
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public static ByteReadBuffer Wrap(Span<byte> buffer)
        {
            return new ByteReadBuffer(buffer);
        }

        public static ByteReadBuffer Wrap(Span<byte> buffer, int length)
        {
            return Wrap(buffer.Slice(0, length));
        }

        public static ByteReadBuffer Wrap(Span<byte> buffer, int offset, int length)
        {
            return Wrap(buffer.Slice(offset, length));
        }
    }
}
